package com.shop.service.impl;

import com.shop.common.Message;
import com.shop.common.ProductStatus;
import com.shop.entity.OrderItem;
import com.shop.entity.Product;
import com.shop.mapper.OrderItemMapper;
import com.shop.mapper.OrderMapper;
import com.shop.mapper.ProductMapper;
import com.shop.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 商品服务实现类
 * 
 * 提供商品相关的业务逻辑处理
 * 
 * @author Shop Management System
 * @version 1.0
 * @since 2024-01-01
 */
@Service
@Transactional
public class ProductServiceImpl implements ProductService {
    
    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;
    @Override
    public List<Product> getAllProducts() {
        return productMapper.findAll();
    }
    
    @Override
    public Product getProductById(Long id) {
        return productMapper.findById(id);
    }
    
    @Override
    public Product findProductByCode(String productCode) {
        return productMapper.findByProductCode(productCode);
    }
    
    @Override
    public Product addProduct(Product product) {
        product.setProductCode(generateProductCode());
        product.setCreatedAt(LocalDateTime.now());
        product.setUpdatedAt(LocalDateTime.now());
        if (product.getStatus() == null) {
            product.setStatus(1);
        }
        if (product.getStockQuantity() == null) {
            product.setStockQuantity(0);
        }
        // 库存为0时默认status为0
        if (product.getStockQuantity() == 0) {
            product.setStatus(0);
        }
        productMapper.insert(product);
        return product;
    }
    
    @Override
    public void updateProduct(Product product) {
        product.setUpdatedAt(LocalDateTime.now());
        productMapper.update(product);
    }
    
    @Override
    public void deleteProduct(Long id) {
        //判断商品是否在起售状态
        Product product = productMapper.findById(id);
        if (product.getStatus().equals(ProductStatus.STATUS_ENABLE)) {
            throw new RuntimeException(Message.PRODUCT_START);
        }
        //判断是否关联了订单
        //查询关联表
        OrderItem orderItem = orderItemMapper.getByProductId(id);
        if (orderItem != null) {
            //关联则抛出关联的异常
            throw new RuntimeException(Message.ORDER_RELATED_PRODUCT);
        }
        //没有则完成删除操作
        productMapper.deleteById(id);
    }
    
    @Override
    public List<Product> searchProducts(String keyword) {
        return productMapper.findByNameContaining(keyword);
    }
    
    @Override
    public List<Product> findProductsByCategory(String category) {
        return productMapper.findByCategory(category);
    }
    
    @Override
    public List<Product> findLowStockProducts(int minStock) {
        return productMapper.findLowStockProducts(minStock);
    }
    
    @Override
    public List<Product> findOutOfStockProducts() {
        return productMapper.findByStock(0);
    }
    
    @Override
    public void updateStock(Long productId, int quantity) {
        Product product = productMapper.findById(productId);
        //判断库存是否充足
        if (product != null) {
            int newStock = product.getStockQuantity() - quantity;
            if (newStock >= 0) {
                productMapper.updateStock(productId, newStock);
            } else {
                throw new RuntimeException(Message.NO_ENOUGH);
            }
        }
    }

    @Override
    public void increaseStock(Long id, int quantity) {
        Product product = productMapper.findById(id);
        if (product != null) {
            int newStock = product.getStockQuantity() + quantity;
            productMapper.updateStock(id, newStock);
        }
    }

    @Override
    public void decreaseStock(Long id, int quantity) {
        Product product = productMapper.findById(id);
        if (product != null) {
            int newStock = product.getStockQuantity() - quantity;
            if (newStock >= 0) {
                productMapper.updateStock(id, newStock);
            } else {
                throw new RuntimeException("库存不足");
            }
        }
    }

    @Override
    public boolean importProductsFromExcel(MultipartFile file) {
        // Implementation needed
        return false;
    }

    @Override
    public byte[] exportProductsToExcel() {
        // Implementation needed
        return new byte[0];
    }

    @Override
    public void importProducts(List<Product> products) {
        for (Product product : products) {
            Product existingProduct = productMapper.findByCode(product.getProductCode());
            if (existingProduct != null) {
                existingProduct.setName(product.getName());
                existingProduct.setDescription(product.getDescription());
                existingProduct.setPrice(product.getPrice());
                existingProduct.setStockQuantity(product.getStockQuantity());
                existingProduct.setCategory(product.getCategory());
                productMapper.update(existingProduct);
            } else {
                productMapper.insert(product);
            }
        }
    }

    @Override
    public List<Product> findProductsByStatus(Integer status) {
        return productMapper.findByStatus(status);
    }

    @Override
    public void changeProductStatus(Long id, Integer status) {
        Product product = productMapper.findById(id);
        if (product != null) {
            product.setStatus(status);
            product.setUpdatedAt(LocalDateTime.now());
            productMapper.update(product);
        }
    }

    private String generateProductCode() {
        return "P" + System.currentTimeMillis();
    }
} 